package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.BusinessException;
import com.mall.common.ResultCode;
import com.mall.model.Order;
import com.mall.model.OrderItem;
import com.mall.model.Product;
import com.mall.repository.OrderItemMapper;
import com.mall.repository.OrderMapper;
import com.mall.repository.ProductMapper;
import com.mall.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    
    private final OrderItemMapper orderItemMapper;
    private final ProductMapper productMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(Order order) {
        // 生成订单号
        order.setOrderNo(generateOrderNo());
        // 设置订单状态
        order.setStatus(0);
        // 保存订单
        save(order);
        
//        // 保存订单详情
//        List<OrderItem> items = order.getItems();
//        for (OrderItem item : items) {
//            // 设置订单ID
//            item.setOrderId(order.getId());
//            // 查询商品信息
//            Product product = productMapper.selectById(item.getProductId());
//            if (product == null) {
//                throw new BusinessException(ResultCode.PRODUCT_NOT_EXIST);
//            }
//            // 设置商品信息
//            item.setProductName(product.getName());
//            item.setProductImage(product.getImage());
//            item.setPrice(product.getPrice());
//            item.setTotalPrice(product.getPrice().multiply(new BigDecimal(item.getQuantity())));
//            // 保存订单详情
//            orderItemMapper.insert(item);
//            // 更新商品库存
//            product.setStock(product.getStock() - item.getQuantity());
//            productMapper.updateById(product);
//        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long id) {
        // 查询订单
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException(ResultCode.ORDER_NOT_EXIST);
        }
        // 检查订单状态
        if (order.getStatus() != 0) {
            throw new BusinessException(ResultCode.ORDER_STATUS_ERROR);
        }
        // 更新订单状态
        order.setStatus(4);
        updateById(order);
        // 恢复商品库存
        List<OrderItem> items = orderItemMapper.selectList(
                new LambdaQueryWrapper<OrderItem>()
                        .eq(OrderItem::getOrderId, id));
        for (OrderItem item : items) {
            Product product = productMapper.selectById(item.getProductId());
            product.setStock(product.getStock() + item.getQuantity());
            productMapper.updateById(product);
        }
    }
    
    @Override
    public void payOrder(Long id) {
        // 查询订单
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException(ResultCode.ORDER_NOT_EXIST);
        }
        // 检查订单状态
        if (order.getStatus() != 0) {
            throw new BusinessException(ResultCode.ORDER_STATUS_ERROR);
        }
        // 更新订单状态
        order.setStatus(1);
        updateById(order);
    }
    
    @Override
    public void shipOrder(Long id) {
        // 查询订单
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException(ResultCode.ORDER_NOT_EXIST);
        }
        // 检查订单状态
        if (order.getStatus() != 1) {
            throw new BusinessException(ResultCode.ORDER_STATUS_ERROR);
        }
        // 更新订单状态
        order.setStatus(2);
        updateById(order);
    }
    
    @Override
    public void confirmOrder(Long id) {
        // 查询订单
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException(ResultCode.ORDER_NOT_EXIST);
        }
        // 检查订单状态
        if (order.getStatus() != 2) {
            throw new BusinessException(ResultCode.ORDER_STATUS_ERROR);
        }
        // 更新订单状态
        order.setStatus(3);
        updateById(order);
    }
    
    @Override
    public Page<Order> getUserOrderPage(Page<Order> page, Long userId, Integer status) {
        // 构建查询条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId);
        if (status != null) {
            wrapper.eq(Order::getStatus, status);
        }
        wrapper.orderByDesc(Order::getCreateTime);
        // 分页查询
        return page(page, wrapper);
    }
    
    private String generateOrderNo() {
        // 生成订单号：时间戳 + 随机数
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                + UUID.randomUUID().toString().substring(0, 8);
    }
} 